import { defineStore } from 'pinia'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import remainingRouter from '@/router/modules/remaining'
import { generateRoute, flatMultiLevelRoutes } from '@/utils/routerHelper'
import { getAsyncRoutes } from '@/api/login'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  dynamicRouter: AppCustomRouteRecordRaw[]
  menuTabRouters: AppRouteRecordRaw[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    dynamicRouter: [],
    menuTabRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      const data = hangdleDelayPath(this.routers)
      const peelOff = data.filter((e) => e.peelOff === 0)
      const peelOn = data.filter((e) => e.peelOff !== 0)
      peelOff.forEach((e) => {
        peelOn.splice(e.index, 0, ...e.children)
      })
      return peelOn
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep([...this.routers, ...this.addRouters]))
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    },
    getDynamicRouter(): AppCustomRouteRecordRaw[] {
      return this.dynamicRouter
    }
  },
  actions: {
    async generateRoutes(): Promise<unknown> {
      return new Promise<void>(async (resolve) => {
        let res: AppCustomRouteRecordRaw[]
        res = await getAsyncRoutes()
        // wsCache.set(
        //   CACHE_KEY.ROLE_ROUTERS,
        //   res.filter((el) => el.mark == 1 || el.mark == 2)
        // )
        this.dynamicRouter = res || []
        const routerMap: AppRouteRecordRaw[] = generateRoute(res as AppCustomRouteRecordRaw[])
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(remainingRouter).concat(this.addRouters)
        resolve()
      })
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}

const hangdleDelayPath = (list) => {
  return list.map((e, index) => {
    if (e.peelOff === 0) {
      e.index = index
      e.children = handleSubPath(e.children, e.path)
    }
    return e
  })
}

const handleSubPath = (list, path) => {
  list.forEach((e) => {
    e.path = `${path}/${e.path}`
  })
  return list
}
